#互联网上的黑客攻击太多了
#我们针对/var/log/secure破解密码的条目， 超过3次，计入/etc/hosts.deny文件中， 把对方IP给禁掉。
#最后把本程序加入cron计划任务 建议每分钟跑一次
import datetime
now=str(datetime.datetime.now())
with open("/var/log/secure",'r') as f:
    x=f.readlines()
#print('hello1')
dict_ip={}
#回溯多少条记录
for item in x[-200:]:
    if "Failed password" in item or "Invalid" in item:
        ip=item.split('from ')[1].split(' ')[0]
        #ip=item.split(' ')[12]
        if ip in dict_ip.keys():
            dict_ip[ip]=dict_ip[ip]+1
        else:
            dict_ip[ip]=1
#print(dict_ip)
black_list=[]
for key in dict_ip.keys():
    #密码输入错误次数
    if dict_ip[key]>3:
        black_list.append(key)
#print(black_list)
#black_list=['1.1.1.1','2.2.2.2','3.3.3.3']
with open("/etc/hosts.deny",'r') as f:
    y=f.readlines()
new=''.join(y)
for item in black_list:
    if item in new:
        pass
    else:
        new=new+"sshd:"+item+":deny #%s \n"%(now)
print(new)
with open("/etc/hosts.deny",'w') as f:
    f.write(new)